import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.scannotation.*

@GrabResolver(name = 'jboss', root = 'https://repository.jboss.org/nexus/content/groups/public/')
@GrabResolver(name = 'spring', root = 'http://maven.springframework.org/release/')


@Grapes([
@Grab(group = 'org.hibernate', module = 'hibernate-core', version = '3.5.6-FINAL'),
@Grab(group = 'org.hibernate', module = 'hibernate-annotations', version = '3.5.6-FINAL'),
@Grab(group = 'javax.persistence', module = 'persistence-api', version = '1.0'),
@Grab(group = 'org.slf4j', module = 'slf4j-simple', version = '1.4.2'),
@Grab(group = 'net.sf.scannotation', module = 'scannotation', version = '1.0.2')
])

def logger = LoggerFactory.getLogger(getClass());

def outputFile = new File('./hockey-game-mysql.sql')
def jarFile = new File('./core/build/libs/core-0.1-SNAPSHOT.jar')

assert jarFile.exists(): "File does not exist ${jarFile.absolutePath}"

if (outputFile.exists()) {
  logger.info("Detected previously generated SQL file. About to delete ${outputFile.name}")
  outputFile.delete()
}

this.getClass().classLoader.rootLoader.addURL(jarFile.toURL())

URL[] urls = [jarFile.toURL()] as URL[]
AnnotationDB db = new AnnotationDB()
db.scanArchives(urls)

if (db.annotationIndex[javax.persistence.Entity.class.name] || db.annotationIndex[javax.persistence.MappedSuperclass.class.name]) {

  def cfg = new org.hibernate.cfg.AnnotationConfiguration()

  def properties = new Properties()
  properties['hibernate.format_sql'] = true
  properties['hibernate.use_sql_comments'] = true
  properties['hibernate.dialect'] = 'org.hibernate.dialect.MySQL5InnoDBDialect'

  cfg.properties = properties
  addClasses(cfg, db.annotationIndex[javax.persistence.MappedSuperclass.class.name], logger)
  addClasses(cfg, db.annotationIndex[javax.persistence.Entity.class.name], logger)

  cfg.buildSessionFactory()

  def exporter = new org.hibernate.tool.hbm2ddl.SchemaExport(cfg)
  exporter.delimiter = ';'
  exporter.format = Boolean.TRUE
  exporter.haltOnError = Boolean.TRUE

  exporter.outputFile = outputFile.absolutePath

  exporter.execute(false, false, false, true);

  assert outputFile.text.length() > 0: 'File is empty'
}
else {
  logger.warn('No annotated classes have been found')
}

private def addClasses(org.hibernate.cfg.AnnotationConfiguration cfg, Set<String> classNames, logger) {
  for (String className: classNames) {

    logger.info "About to add annotated class '$className' to Hibernate configuration"

    cfg.addAnnotatedClass(getClass().getClassLoader().loadClass(className))
  }
}






